<template>
  <Financial
    title="对账单管理"
    add-btn-text="新增对账单"
    :columns="columns"
    :get-page-url="Api.checkBillPage"
    :cud-url="Api.checkBill"
    create-title="新增对账单"
    update-title="编辑对账单"
    delete-message="确认删除该对账单吗？"
    :model="model"
    :model-form-setting="modelFormSetting"
    review-api-key="checkBillReview"
    nullify-api-key="checkBillNullify"
    :get-detail="getDetail"
    :detail-modal-options="detailModalOptions"
    @before-update-model="beforeUpdateModel"
    @before-ok="beforeOk"
    @show-detail="showDetail"
  >
    <template #detailCenter>
      <div class="h-120">
        <sl-table row-key="_uuid" :columns="docColumns" :data-source="docData">
          <template #bodyCell="{ record, column }">
            <FitTitleCell :record="record" :column="column" />
          </template>
        </sl-table>
      </div>
    </template>
  </Financial>
</template>
<script setup lang="ts">
import { h, ref } from "vue";
import Financial from "/@/views/common/Financial/Financial.vue";
import { message, TableColumnProps } from "ant-design-vue";
import { Api, changeFinancialStatus, getFinancialDetail } from "/@/api/main/financial";
import { DetailModalOptions, DocItem, FinancialItem, FinancialType, InvoiceType } from "/@/api/main/financial/models";
import { CURDAction, CURDModalEvent, FormItemComponentType, FormItemData } from "/@/components/CURDDialog/models";
import { enumToOptions, getLabelByValueFromEnum, handleDateRowRender } from "/@/utils/common";
import { getSupplierList } from "/@/api/main/pis";
import dayjs from "dayjs";
import { ReceiptStatus } from "/@/api/main/pis/models";
import { SelectOptionItem } from "/@/types/antd";
import { DEFAULT_IMG_BASE64_STR } from "/@/utils/file";
import TableFormItem from "./TableFormItem.vue";
import { useCheckBill } from "./useCheckBill";
import InfoModal from "/@/components/InfoModal";

const columns = ref<TableColumnProps<FinancialItem>[]>([
  {
    title: "对账账期",
    dataIndex: "reconciliationPeriod",
  },
  {
    title: "对账单号",
    dataIndex: "orderNo",
  },
  {
    title: "供应商",
    dataIndex: "supplierName",
  },
  {
    title: "单据数量",
    dataIndex: "docNum",
  },
  {
    title: "帐单数量",
    dataIndex: "billsNum",
  },
  {
    title: "帐单金额",
    dataIndex: "totalBillAmount",
  },
  {
    title: "拟结算日期",
    dataIndex: "proposedSettlementDate",
    customRender: handleDateRowRender,
  },
  {
    title: "状态",
    dataIndex: "status",
  },
  {
    title: "备注",
    dataIndex: "remark",
  },
  {
    title: "生成人",
    key: "createInfo",
  },
  {
    title: "审核人",
    key: "reviewInfo",
  },
  {
    title: "推送人",
    key: "pushInfo",
  },
  {
    title: "操作",
    key: "oper",
    fixed: "right",
  },
  {
    title: "",
    key: "extraOper",
    fixed: "right",
  },
]);

const model = ref<Partial<FinancialItem>>({
  reconciliationPeriod: "",
  _proposedSettlementDate: null,
  supplierId: null,
  _details: null,
  remark: "",
});

const modelFormSetting = ref<FormItemData<Partial<FinancialItem>>[]>([
  {
    key: "reconciliationPeriod",
    type: FormItemComponentType.DATEPICKER,
    props: {
      picker: "month",
      valueFormat: "YYYYMM",
    },
    required: true,
  },
  {
    key: "_proposedSettlementDate",
    label: "拟结算日期",
    type: FormItemComponentType.DATEPICKER,
    props: {
      valueFormat: null,
    },
    required: true,
  },
  {
    key: "remark",
    label: "备注",
    type: FormItemComponentType.TEXTAREA,
  },
  {
    key: "supplierId",
    label: "供应商",
    type: FormItemComponentType.SELECT,
    props: {
      options: [],
    },
    async getData() {
      const data = await getSupplierList();
      return data
        ? data.map((item) => ({
            label: item.name,
            value: item.id,
            key: item.id,
          }))
        : [];
    },
    required: false,
  },
  {
    key: "_details",
    label: "单据列表",
    holdRow: true,
    required: true,
    customComponent: h(TableFormItem),
  },
]);

function beforeUpdateModel(record: FinancialItem) {
  record._details = {
    details: record.details as Partial<DocItem>[],
    startPeriod: record.startPeriod as number,
    endPeriod: record.endPeriod as number,
  };
  record._proposedSettlementDate = dayjs(record.proposedSettlementDate);
}

function beforeOk({ action, model }: CURDModalEvent<Partial<FinancialItem>>) {
  if (model) {
    if (action === CURDAction.CREATE) {
      model.status = ReceiptStatus.waiting;
    }
    model.proposedSettlementDate = model._proposedSettlementDate?.valueOf();
    delete model._proposedSettlementDate;
    const _details = model._details;
    if (_details) {
      let billsNum = 0;
      let totalBillAmount = 0;
      const keys = ["id", "reconciliationId", "orderId", "type"];
      const newDetails: Partial<DocItem>[] = [];
      _details.details.forEach((el) => {
        totalBillAmount += el.amount || 0;
        billsNum += el.quantity || 0;
        newDetails.push({
          reconciliationId: el.reconciliationId,
          orderId: el.orderId,
          type: el.type,
          supplierId: el.supplierId,
        });
      });
      model.startPeriod = model._details?.startPeriod;
      model.endPeriod = model._details?.endPeriod;
      delete model._details;
      model.docNum = newDetails.length;
      model.totalBillAmount = totalBillAmount;
      model.billsNum = billsNum;
      model.details = newDetails;
    }
  }
}
async function getDetail(record: Partial<FinancialItem>) {
  const data = await getFinancialDetail({ reconciliationId: record.id }, FinancialType.checkBill);
  return data || {};
}
/**
 * detail modal
 */
const { docColumns } = useCheckBill();
const detailModalOptions = ref<DetailModalOptions>({
  triggerKeys: ["orderNo"],
  title: "对账单详情",
  desKeys: [
    "reconciliationPeriod",
    "orderNo",
    "supplierName",
    "docNum",
    "billsNum",
    "totalBillAmount",
    { key: "proposedSettlementDate", isDate: true },
  ],
  loading: false,
  data: {},
});
const docData = ref<any>([]);
async function showDetail(record: Partial<FinancialItem>) {
  detailModalOptions.value.loading = true;
  const data = await getDetail(record);
  detailModalOptions.value.loading = false;
  if (data) {
    const copy = { ...record };
    Object.assign(copy, data);
    copy.details?.forEach((el) => {
      el._uuid = [el.orderId, el.type].join("-");
    });
    docData.value = copy.details;
    detailModalOptions.value.data = copy;
  }
}
</script>
